<template>
  <div class="page store-choice">
    <div class="scroll-view">
      <customHeader middleTitle="选择门店" @leftCallBack="back"/>
      <div class="tip-msg" v-if="tipMsg&&notPassMini">
        <i class="zhk-order_fa"></i>
        <span>{{tipMsg}}</span>
      </div>
      <searchBar @search="searchCallbck"/>
      <div class="scroll-ct page-body">
        <div
          class="store-choice-list"
          v-for="(item,index) in listData"
          :key="index"
          v-show="item.visible"
        >
          <div class="head">{{item.head}}</div>
          <div
            class="item"
            @click="storeItemChoice(childitem.key,childitem.data.disabled)"
            v-for="(childitem,index) in item.children"
            :key="index"
          >
            <div
              :class="childitem.data.disabled?'item-ct disabled':'item-ct'"
              v-show="childitem.visible"
            >
              <span :class="childitem.select?'list_select label':'list-wx label'">
                <template v-if="multipleChoice">
                  <i v-if="!childitem.select" class="zhk-list-wx"></i>
                  <i v-if="childitem.select" class="zhk-list_select"></i>
                </template>
                <span>{{childitem.label}}</span>
                <span v-if="childitem.data.tag" class="tag">{{childitem.data.tag}}</span>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="multiple-ope" v-if="multipleChoice">
        <div class="check-all" @click="choiceAll">
          <i class="zhk-list-wx" v-show="!selectAllFlag"></i>
          <i class="zhk-list_select" v-show="selectAllFlag"></i>
          <span>全选</span>
        </div>
        <div
          class="select-amount"
          :class="{disabled:selectCount===0}"
          @click="submit"
        >确定&nbsp;({{selectCount}})</div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Popup, Toast, MessageBox } from "mint-ui";
import customHeader from "../../components/header/header";
import searchBar from "../../components/searchBar/searchBar";
Vue.component(Popup.name, Popup);
export default {
  name: "StoreChoice",
  data() {
    return {
      loadding:false,//提交中
      selectCount: 0,//门店选中数
      listData: [],//门店列表数据
      popupVisible: false,
      storeName: "选择门店",
      selectAllFlag: false,
      singleChoiceAllFlag: false,
      dataSource: [],//接口返回的data
      currentSelect: [], //用于点返回记录还原数据
      notPassMini: false,//不符合小程序条件的门店
      tipMsg:"部分门店不符合开通条件，可联系销售人员解决"
    };
  },
  props: {
    multipleChoice: {//是否为多选
      type: Boolean,
      default: true
    },
    multipleSelectAll: {//多选下，默认是否为全选
      type: Boolean,
      default: true
    },
    hasTotal: {//是否显示全部门店
      type: Boolean,
      default: true
    },
    // tipMsg: {//提示消息
    //   default: ""
    // },

    //是否过滤掉其他状态门店，只显示审核通过的门店
    statusFilter: {
      type: Boolean,
      default: false
    },
    //门店列表的请求接口地址（默认请求：/newapp/shop/getShopSelect.do）
    reqUrl: {
      type: String,
    }
  },
  mounted() {

  },
  methods: {
    searchCallbck(v) {
      if (v) {
        //有值搜索
        for (let city of this.listData) {
          let hasVisible = false;
          for (let store of city.children) {
            if (store.label.indexOf(v) !== -1) {
              store.visible = true;
              hasVisible = true;
            } else {
              store.visible = false;
            }
          }
          city.visible = hasVisible;
        }
      } else {
        //无值还原
        for (let city of this.listData) {
          city.visible = true;
          for (let store of city.children) {
            store.visible = true;
          }
        }
      }
    },
    //确定
    submit() {
      let selectArr = [];
      const listData = this.listData;

      for (let city of listData) {
        for (let store of city.children) {
          if (store.select === true) {
            selectArr.push(store.key);
          }
        }
      }
      if (selectArr.length == 0) {
        Toast("请选择门店");
        return;
      }
      this.currentSelect = selectArr;

      this.updateStatus(selectArr);
    },
    //开通
    updateStatus(shopIdArr) {
       this.loadding=true;
      this.ajax({
        url: `/applet/manager/updateShopService.do`,
        type: "post",
        data: {shopIds:shopIdArr},
        controlLoading: true,
      })
        .then(response => {
           this.loadding=false;
          if (response && response.success) {
            MessageBox({
              title: "操作成功",
              message: "为保证会员获取以及营销等功能的正常使用，请到【门店管理】重新下载二维码物料",
              showCancelButton: false,
              closeOnClickModal: false,
              confirmButtonText: "进入门店管理",
            }).then(action => {
              if (action === "confirm") {
                this.$router.push({ path: "/storeManage" });
              }
            });
          } else {
            Toast(response.msg);
          }
        })
        .catch( (err)=> {
           this.loadding=false;
        });
    },
    //返回（不传值）
    back() {
      this.$router.back();
    },
    //选择全部
    choiceAll() {
      const selectAllFlag = this.selectAllFlag;
      this.selectAllFlag = !selectAllFlag;
      for (let i = 0; i < this.listData.length; i++) {
        for (let j = 0; j < this.listData[i].children.length; j++) {
          this.listData[i].children[j].select = !selectAllFlag;
        }
      }
      this.getSelectCount(this.listData);
    },
    //门店选择
    storeItemChoice(key, disabled) {
      if (disabled) {
        return false;
      }
      const listData = this.listData;
      if (this.multipleChoice) {
        //多选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].key == key) {
              let flag = this.listData[i].children[j].select;
              this.listData[i].children[j].select = !flag;
            }
          }
        }
        this.getSelectCount(this.listData);
        //如果每一项都选中全部门店勾选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].select == false) {
              this.selectAllFlag = false;
              return;
            } else {
              this.selectAllFlag = true;
            }
          }
        }

      } else {
        this.singleChoiceAllFlag = false;
        //单选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].key == key) {
              let flag = this.listData[i].children[j].select;
              this.listData[i].children[j].select = true;
            } else {
              this.listData[i].children[j].select = false;
            }
          }
        }
      }
    },
    checkDataSource(data, currentSelect) {
      let shopList = [];
      let checkCount = 0;
      let storeCount = 0;
      if (data != null && JSON.stringify(data) != "{}") {
        for (let cityName in data) {
          let childrenList = [];
          if (data[cityName] != null && data[cityName].length > 0) {
            for (let i = 0; i < data[cityName].length; i++) {
              //未开通小程序或者不满足条件的门店（mini：已开通小程序 true:开通；  passMini：符合小程序开通 true:符合 false:不符合）
              const isChecked = data[cityName][i]['mini'];
              if(data[cityName][i]['passMini']===false){
                this.notPassMini=true;
              }

              if (data[cityName][i]['passMini']) {
                childrenList.push({
                  visible: true,
                  key: data[cityName][i].shopId,
                  label: data[cityName][i].shopName,
                  select: isChecked,
                  data: data[cityName][i]
                });
                if (isChecked) {
                  checkCount = checkCount + 1;
                }
              }
            }
          }
          childrenList.length > 0 &&
            shopList.push({
              head: cityName,
              children: childrenList,
              visible: true
            });
          storeCount = storeCount + childrenList.length;
        }
      }
      this.selectAllFlag =storeCount!=0&&checkCount === storeCount ? true : false;
      this.selectCount = checkCount;
      return shopList;
    },
    getData(callBack) {
      const url =`/applet/manager/queryCityShopList.do?queryType=${2}&serviceCode=${9}`;
      this.ajax({
        url: url,
        type: "get",
        data: {},
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            const data = res.resultObject;
            this.dataSource = data;
            this.listData = this.checkDataSource(data, this.currentSelect);
            callBack && callBack();
          }
        })
        .catch(function (err) {
          
        });
    },
    //当前选中的门店数
    getSelectCount(listData) {
      let selectCount = 0;
      for (let i = 0; i < listData.length; i++) {
        for (let j = 0; j < listData[i].children.length; j++) {
          if (listData[i].children[j].select) {
            selectCount = selectCount + 1;
          }
        }
      }
      this.selectCount = selectCount;
    }
  },
  components: {
    customHeader,
    searchBar
  },
  created() {
    this.getData();
  },
};
</script>

<style lang="scss" scoped>
@import "../../components/StoreChoice/StoreChoice.scss";
</style>
